package cn.codenest.rabbitmqprovider.service.impl;

import cn.codenest.rabbitmqprovider.service.SpringRbmqService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author ：Hyman
 * @date ：Created in 2020/12/16 16:45
 * @description：
 * @modified By：
 * @version: $
 */
@Service
public class SpringRbmqServiceImpl implements SpringRbmqService {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public void sendMsg(Integer type) throws IOException {
        /*消息发送到Exchange的回调*/
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {

            }
        });

        /*消息发送到队列失败回退时回调*/
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {

            }
        });

        /*直连也一定要用Routing key*/
        if (type == 1) {
            MessageProperties messageProperties = new MessageProperties();
            // 设置过期时间，单位：毫秒,30分钟
            messageProperties.setExpiration("1800000");
            messageProperties.setContentType("text/plain");
            messageProperties.setContentEncoding("UTF-8");
            byte[] msgBytes = "TestDirectMessage".getBytes();
            Message message = new Message(msgBytes, messageProperties);
            rabbitTemplate.convertAndSend("TestDirectExchange", "TestDirectRouting",message);
        } else if (type == 2) {
            rabbitTemplate.convertAndSend("TestTopicExchange", "TestTopicRouting", "TestTopicMessage");
        }else {
            rabbitTemplate.convertAndSend("TestFanoutExchange", "","TestFanoutMessage");
        }

    }
}
